<template>
  <div class="container">
    <el-form inline>
      <el-form-item label="部门名称">
        <el-input v-model="filter.name" placeholder="请输入部门名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filter.status" placeholder="部门状态" style="width:140px;" clearable>
          <el-option label="正常" value="Active"></el-option>
          <el-option label="禁用" value="Inactive"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="list" icon="Search">搜索</el-button>
        <el-button @click="reset" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" plain icon="Plus" @click="add">新增</el-button>
      <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
    </el-row>

    <el-table empty-text="暂无部门数据" :data="departmentList" style="width:100%;margin-top:10px;" row-key="departmentId" v-if="refreshTable"
              :default-expand-all="isExpandAll">
      <el-table-column prop="departmentName" label="部门名称" ></el-table-column>
      <el-table-column prop="sort" label="排序" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 'Active'" type="primary">正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="edit(scope.row)">修改</el-button>
          <el-button type="primary" link icon="Plus" @click="add(scope.row)">新增</el-button>
          <el-button type="danger" link icon="Delete" @click="del(scope.row)" v-if="scope.row.parentDepartmentId!=undefined">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    

    <el-dialog :title="title" v-model="dialogVisible" width="750px" destroy-on-close append-to-body draggable>
      <el-form ref="form1" :model="formModel" label-width="100px">
        <el-form-item label="上级部门" prop="parentDepartmentId">
          <el-tree-select v-model="formModel.parentDepartmentId" :render-after-expand="false" :default-expand-all="true"
                          :data="departmentList" placeholder="请选择上级部门" style="width:300px;" @node-click="onNodeClick"
                          :props="departmentSelectProps" clearable/>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName"
                      :rules="[{required:true,message:'请输入部门名称',trigger:'blur'}]">
          <el-input v-model="formModel.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort" :rules="[{required:true,message:'请输入排序',trigger:'blur'}]">
          <el-input type="number" min="1" v-model="formModel.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formModel.manager" placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formModel.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="mailbox">
          <el-input v-model="formModel.mailbox" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="部门状态" prop="status" :rules="[{required:true,message:'请选择状态',trigger:'blur'}]">
          <el-select v-model="formModel.status" placeholder="请选择状态" style="width:140px;" clearable>
            <el-option label="正常" value="Active"></el-option>
            <el-option label="禁用" value="Inactive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime" v-if="formModel.departmentId==undefined">
          <el-date-picker v-model="formModel.createTime" type="datetime" placeholder="选择日期时间" style="width:300px;"
                          value-format="YYYY-MM-DD HH:mm:ss"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitSave">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {onMounted, ref,nextTick} from "vue";
import axios from 'axios';
import {ElMessage, ElMessageBox} from "element-plus";

const API = 'http://localhost:1111';

interface Filter {
  name: string
  status: string
}

const filter = ref<Filter>({
  name: '',
  status: ''
})
const isExpandAll = ref<boolean>(true);
const refreshTable = ref<boolean>(true);
const departmentList = ref([])


/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

function reset(){
  filter.value = {
    name: '',
    status: ''
  }
  list()
}

async function list() {
  try {
    const res = await axios.post(API + '/department/list', filter.value)
    if (res.data.code === 0) {
      departmentList.value = res.data?.data?.list
      console.log(res.data?.data?.list)
    }
    console.log(res.data)
  } catch (error) {
    console.error("获取数据时出错!", error);
  }
}

onMounted(() => {
  list()
})

interface FormModel {
  departmentId: number
  departmentName: string
  sort: number
  status: string
  parentDepartmentId: number
  manager: string
  phone: string
  mailbox: string
  createTime: string
}

const title = ref<string>('新增部门')
const dialogVisible = ref<boolean>(false)
const form1 = ref<any>()
const formModel = ref<FormModel>({
  departmentId: undefined,
  departmentName: '',
  sort: 1,
  status: 'Active',
  parentDepartmentId: undefined,
  manager: '',
  phone: '',
  mailbox: '',
  createTime: ''
})
const departmentSelectProps = ref({
  value: 'departmentId',
  label: 'departmentName',
  children: 'children'
})

function add(row?: any) {
  title.value = '新增部门'
  formModel.value = {
    departmentId: undefined,
    departmentName: '',
    sort: 1,
    status: 'Active',
    parentDepartmentId: row != undefined ? row.departmentId : undefined,
    manager: '',
    phone: '',
    mailbox: '',
    createTime: ''
  }
  dialogVisible.value = true
}

function edit(row: any){
  title.value = '修改部门'
  formModel.value = {
    departmentId: row.departmentId,
    departmentName: row.departmentName,
    sort: row.sort,
    status: row.status,
    parentDepartmentId: row.parentDepartmentId,
    manager: row.manager,
    phone: row.phone,
    mailbox: row.mailbox,
    createTime: row.createTime
  }
  dialogVisible.value = true
}

function submitSave() {
  form1.value.validate(async (valid: boolean) => {
    if (!valid) return
    if (formModel.value.departmentId == undefined) {
      if (formModel.value.parentDepartmentId == undefined) {
        ElMessage({
          message: '请选择上级部门',
          type: 'error'
        })
        return
      }
    }else{
      if(formModel.value.parentDepartmentId != undefined){
        if(formModel.value.parentDepartmentId==formModel.value.departmentId){
          ElMessage({
            message: '上级部门不能是自己',
            type: 'error'
          })
          return
        }
      }
    }
    const action = formModel.value.departmentId == undefined ? '/department/create' : '/department/update'
    const actionTitle = formModel.value.departmentId == undefined ? '新增' : '修改'
    const res = await axios.post(API + action, formModel.value)
    if (res.data.code == 0) {
      ElMessage({
        message: actionTitle + '成功',
        type: 'success'
      })
      dialogVisible.value = false
      await list()
    } else {
      ElMessage({
        message: actionTitle + '失败',
        type: 'error'
      })
    }
  })
}


function del(row: any){
  ElMessageBox.confirm('此操作将永久删除'+row.departmentName+', 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await axios.get(API + '/department/delete/'+row.departmentId)
    if (res.data.code == 0) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      await list()
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error'
      })
    }
  })
}

function onNodeClick(node:any){
  formModel.value.parentDepartmentId=node.departmentId
}

</script>

<style scoped lang="scss">
.container {
  width: 100%;
  text-align: left;
}
</style>